#!/usr/bin/python3
# -*- encoding:utf-8 -*-
# author: king
# create date time: 2024/4/14 下午10:30
import datetime
import os
import sys
import logging
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler

datetime_obj = datetime.datetime.now()


class CustomLogger(object):
    def __init__(self, **kwargs):
        self.log_name = kwargs.get("log_name") or __name__
        self.log_path = kwargs.get("log_path") or "logs"
        self.log_level = kwargs.get("log_level") or logging.DEBUG
        self.formatter = kwargs.get("formatter") or "%(asctime)s - %(filename)s:%(funcName)s:%(lineno)d - %(levelname)s - %(message)s"
        self.when = kwargs.get("when") or "D"
        self.interval = kwargs.get("interval") or 1
        self.backup_count = kwargs.get("backup_count") or 7
        self.log_file_encoding = kwargs.get("log_file_encoding") or "utf-8"
        self.fmt = logging.Formatter(self.formatter)
        self.new_log_path = os.path.join(self.log_path, datetime_obj.strftime("%Y%m%d"))

        if not os.path.exists(self.new_log_path):
            os.makedirs(self.new_log_path, exist_ok=True)

        self.logger = logging.getLogger(self.log_name)

        if not self.logger.handlers:
            self.logger.setLevel(self.log_level)
            self.console_output()
            self.info_log_file_output()
            self.error_log_file_output()

    def console_output(self):
        """
        :return:
        :author: king
        :create date time: 2024/4/14 下午10:34
        """
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(self.fmt)
        console_handler.setLevel(self.log_level)
        self.logger.addHandler(console_handler)

    def info_log_file_output(self):
        """
        :return:
        :author: king
        :create date time: 2024/4/14 下午10:36
        """
        info_file_path = os.path.join(self.new_log_path, f"info_{self.log_name}_{datetime_obj.strftime('%Y%m%d')}.log")
        info_file_handler = TimedRotatingFileHandler(
            filename=info_file_path,
            when=self.when,
            interval=self.interval,
            backupCount=self.backup_count,
            encoding=self.log_file_encoding,
        )
        info_file_handler.setFormatter(self.fmt)
        info_file_handler.setLevel(self.log_level)
        info_file_handler.addFilter(lambda record: record.levelno <= 30)
        self.logger.addHandler(info_file_handler)

    def error_log_file_output(self):
        """
        :return:
        :author: king
        :create date time: 2024/4/14 下午10:51
        """
        error_file_path = os.path.join(self.new_log_path, f"error_{self.log_name}_{datetime_obj.strftime('%Y%m%d')}.log")
        error_file_handler = TimedRotatingFileHandler(
            filename=error_file_path,
            when=self.when,
            interval=self.interval,
            backupCount=self.backup_count,
            encoding=self.log_file_encoding,
        )
        error_file_handler.setFormatter(self.fmt)
        error_file_handler.setLevel(self.log_level)
        error_file_handler.addFilter(lambda record: record.levelno > 30)
        self.logger.addHandler(error_file_handler)


def main():
    """程序入口"""
    cl = CustomLogger()
    cl.logger.debug("debug")
    cl.logger.info("info")
    cl.logger.error("error")
    cl.logger.warning("warning")
    cl.logger.critical("critical")


if __name__ == "__main__":
    main()
